<template>
  <div class="exam-result-container">
    <el-card>
      <template #header>
        <div class="result-header">
          <span class="result-title">{{ examResult.paperName }}</span>
          <div class="result-score">
            <span class="score-label">总分：</span>
            <span class="score-value">{{ examResult.totalScore }} 分</span>
          </div>
        </div>
      </template>
      
      <div v-loading="loading" element-loading-text="加载结果中..." class="result-content-wrapper">
        <div v-if="!loading" class="result-content">
        <div class="exam-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="试卷名称">{{ examResult.paperName }}</el-descriptions-item>
            <el-descriptions-item label="开始时间">{{ formatDateTime(examResult.startTime) }}</el-descriptions-item>
            <el-descriptions-item label="结束时间">{{ formatDateTime(examResult.endTime) }}</el-descriptions-item>
            <el-descriptions-item label="总分">{{ examResult.totalScore }} 分</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="questions-section">
          <div class="section-title">答题详情</div>
          
          <div
            v-for="(question, index) in examResult.questions"
            :key="question.questionId"
            class="question-result-item"
          >
            <div class="question-header">
              <span class="question-number">第 {{ index + 1 }} 题</span>
              <span class="question-type">{{ getQuestionTypeLabel(question.type) }}</span>
              <span class="question-score">
                得分：<span :class="getScoreClass(question.score)">{{ question.score }} 分</span>
              </span>
            </div>
            
            <div class="question-content">
              <div class="question-text">{{ question.content }}</div>
              
              <!-- 选择题显示选项 -->
              <div v-if="question.options" class="question-options">
                <div
                  v-for="(option, key) in question.options"
                  :key="key"
                  class="option-item"
                  :class="getOptionClass(question, key)"
                >
                  {{ key }}. {{ option }}
                  <span v-if="isCorrectOption(question, key)" class="correct-mark">✓</span>
                  <span v-if="isSelectedOption(question, key)" class="selected-mark">您选择的</span>
                </div>
              </div>
              
              <!-- 答案显示 -->
              <div class="answer-section">
                <div class="answer-row">
                  <span class="answer-label">正确答案：</span>
                  <span class="correct-answer">{{ question.correctAnswer }}</span>
                </div>
                <div class="answer-row">
                  <span class="answer-label">您的答案：</span>
                  <span class="student-answer" :class="getAnswerClass(question)">
                    {{ question.studentAnswer || '未作答' }}
                  </span>
                </div>
                <div v-if="question.score > 0" class="answer-row">
                  <span class="answer-label">得分：</span>
                  <span class="score-text">{{ question.score }} 分</span>
                </div>
              </div>
              
              <!-- 解析 -->
              <div v-if="question.analysis" class="analysis-section">
                <div class="analysis-title">解析：</div>
                <div class="analysis-content">{{ question.analysis }}</div>
              </div>
              
              <!-- 教师评语 -->
              <div v-if="question.teacherComment" class="comment-section">
                <div class="comment-title">教师评语：</div>
                <div class="comment-content">{{ question.teacherComment }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="action-buttons">
          <el-button @click="handleBack">返回考试列表</el-button>
          <el-button type="primary" @click="handleViewScores">查看所有成绩</el-button>
        </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getExamResult, type ExamResult as ExamResultType } from '../../api/exam'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const examResult = ref<ExamResultType>({
  examId: 0,
  paperName: '',
  startTime: '',
  endTime: '',
  totalScore: 0,
  questions: []
})

// 获取考试结果
const fetchExamResult = async () => {
  loading.value = true
  try {
    const examId = parseInt(route.params.examId as string)
    const res = await getExamResult(examId)
    examResult.value = res.data
  } catch (error: any) {
    ElMessage.error(error.message || '获取考试结果失败')
    router.back()
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取题目类型标签
const getQuestionTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    single: '单选题',
    multiple: '多选题',
    judge: '判断题',
    fill: '填空题',
    essay: '简答题'
  }
  return typeMap[type] || type
}

// 获取得分样式类
const getScoreClass = (score: number) => {
  if (score > 0) {
    return 'score-correct'
  }
  return 'score-wrong'
}

// 获取答案样式类
const getAnswerClass = (question: any) => {
  const studentAnswer = question.studentAnswer || ''
  const correctAnswer = question.correctAnswer || ''
  
  if (question.type === 'multiple') {
    // 多选题需要比较集合
    const studentAnswers = studentAnswer.split(',').sort().join(',')
    const correctAnswers = correctAnswer.split(',').sort().join(',')
    return studentAnswers === correctAnswers ? 'answer-correct' : 'answer-wrong'
  }
  
  return studentAnswer.toLowerCase() === correctAnswer.toLowerCase() ? 'answer-correct' : 'answer-wrong'
}

// 判断是否为正确答案选项
const isCorrectOption = (question: any, key: string): boolean => {
  const correctAnswer = question.correctAnswer || ''
  if (question.type === 'multiple') {
    return correctAnswer.split(',').includes(key)
  }
  return correctAnswer === key
}

// 判断是否为选中的选项
const isSelectedOption = (question: any, key: string): boolean => {
  const studentAnswer = question.studentAnswer || ''
  if (question.type === 'multiple') {
    return studentAnswer.split(',').includes(key)
  }
  return studentAnswer === key
}

// 获取选项样式类
const getOptionClass = (question: any, key: string): string => {
  const isCorrect = isCorrectOption(question, key)
  const isSelected = isSelectedOption(question, key)
  
  if (isCorrect && isSelected) {
    return 'option-correct'
  } else if (isCorrect && !isSelected) {
    return 'option-missed'
  } else if (!isCorrect && isSelected) {
    return 'option-wrong'
  }
  return ''
}

// 返回考试列表
const handleBack = () => {
  router.push({ name: 'ExamList' })
}

// 查看所有成绩
const handleViewScores = () => {
  router.push({ name: 'ExamScores' })
}

onMounted(() => {
  fetchExamResult()
})
</script>

<style scoped>
.exam-result-container {
  padding: 20px;
  overflow: visible;
}

.exam-result-container :deep(.el-card) {
  overflow: visible;
  height: auto;
  max-height: none;
}

.exam-result-container :deep(.el-card__body) {
  overflow: visible;
  height: auto;
  max-height: none;
  padding: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-title {
  font-size: 20px;
  font-weight: bold;
}

.result-score {
  display: flex;
  align-items: center;
  gap: 10px;
}

.score-label {
  font-size: 16px;
}

.score-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.result-content-wrapper {
  min-height: 400px;
}

.result-content {
  overflow: visible;
}

.exam-info {
  margin-bottom: 30px;
}

.questions-section {
  margin-top: 30px;
  overflow: visible;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.question-result-item {
  margin-bottom: 30px;
  padding: 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.question-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.question-number {
  font-weight: bold;
  font-size: 16px;
}

.question-type {
  color: #409eff;
}

.question-score {
  margin-left: auto;
}

.score-correct {
  color: #67c23a;
  font-weight: bold;
}

.score-wrong {
  color: #f56c6c;
}

.question-content {
  padding-left: 20px;
}

.question-text {
  font-size: 15px;
  line-height: 1.6;
  margin-bottom: 15px;
}

.question-options {
  margin: 15px 0;
}

.option-item {
  padding: 10px;
  margin-bottom: 8px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  position: relative;
}

.option-correct {
  background-color: #f0f9ff;
  border-color: #67c23a;
  color: #67c23a;
}

.option-wrong {
  background-color: #fef0f0;
  border-color: #f56c6c;
  color: #f56c6c;
}

.option-missed {
  background-color: #fff7e6;
  border-color: #e6a23c;
  color: #e6a23c;
}

.correct-mark {
  margin-left: 10px;
  color: #67c23a;
  font-weight: bold;
}

.selected-mark {
  margin-left: 10px;
  font-size: 12px;
  color: #409eff;
}

.answer-section {
  margin: 20px 0;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.answer-row {
  margin-bottom: 10px;
}

.answer-row:last-child {
  margin-bottom: 0;
}

.answer-label {
  font-weight: bold;
  margin-right: 10px;
}

.correct-answer {
  color: #67c23a;
  font-weight: bold;
}

.student-answer {
  font-weight: bold;
}

.answer-correct {
  color: #67c23a;
}

.answer-wrong {
  color: #f56c6c;
}

.score-text {
  color: #409eff;
  font-weight: bold;
}

.analysis-section {
  margin-top: 15px;
  padding: 15px;
  background-color: #f0f9ff;
  border-radius: 4px;
}

.analysis-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #409eff;
}

.analysis-content {
  line-height: 1.6;
  color: #606266;
}

.comment-section {
  margin-top: 15px;
  padding: 15px;
  background-color: #fff7e6;
  border-radius: 4px;
}

.comment-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #e6a23c;
}

.comment-content {
  line-height: 1.6;
  color: #606266;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}
</style>

